import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:pwd_keeper/global.dart';
import 'package:pwd_keeper/pages/pwd/pwd_item.dart';
import 'package:pwd_keeper/manager/pwd_keeper_manager.dart';

class PwdKeeperListPage extends StatefulWidget {
  PwdKeeperListPage({Key key, @required this.searchText}) : super(key: key);
  final String searchText;

  @override
  _PwdKeeperListPageState createState() => _PwdKeeperListPageState();
}

class _PwdKeeperListPageState extends State<PwdKeeperListPage> {
  @override
  void initState() {
    super.initState();
  }

  bool searchMatch(pwdKeeper, searchText) {
    return pwdKeeper['account'].contains(searchText) ||
        pwdKeeper['desc'].contains(searchText) ||
        pwdKeeper['link'].contains(searchText);
  }

  List<Widget> getChildrenList(allPwdKeeper) {
    List<Widget> _childrenList = [];
    List.generate(allPwdKeeper.length, (index) {
      String pwdKeeperString = json.encode(allPwdKeeper[index]);
      final pwdKeeper = json.decode(pwdKeeperString);
      _childrenList.add(Offstage(
          offstage: !searchMatch(pwdKeeper, widget.searchText),
          child: PwdKeeperItem(pwdKeeper: pwdKeeper)));
    });
    return _childrenList;
  }

  @override
  Widget build(BuildContext context) {
    PwdKeeperManager _pwdKeeperManager = Provider.of<PwdKeeperManager>(context);
    return _pwdKeeperManager.allPwdKeeper.length > 0
        ? SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Column(
                  children: getChildrenList(_pwdKeeperManager.allPwdKeeper),
                ),
              ],
            ),
          )
        : Center(
            child: Text(
              "请添加新的密码管理项",
              style: TextStyle(
                color: Global.fontSecondColor,
              ),
            ),
          );
  }
}
